<template>
  <div class="node-container">
    <div
        class="node-content"
        :style="{ paddingLeft: depth * 20 + 'px' }"
        :class="{
        selected: node.id === selectedId,
        'has-children': hasChildren
      }"
        @click.stop="toggleNode(node.id)"
    >
      <span class="node-title">{{ node.title }}</span>
      <span v-if="hasChildren" class="toggle-icon">
        {{ node.expanded ? '−' : '+' }}
      </span>
    </div>

    <div v-if="node.expanded && hasChildren" class="children-container">
      <directory-node
          v-for="child in node.children"
          :key="child.id"
          :node="child"
          :depth="depth + 1"
          :selected-id="selectedId"
          @select="handleChildSelect"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import type { TreeNode } from '@/types/treeType.ts';

const props = defineProps<{
  node: TreeNode
  depth: number
  selectedId: string
}>();

const emit = defineEmits<{
  (e: 'select', node: TreeNode): void
}>();

const hasChildren = computed(() =>
    !!props.node.children && props.node.children.length > 0
);

const toggleNode = (id: string) => {
  if (hasChildren.value) {
    props.node.expanded = !props.node.expanded
  }
  emit('select', props.node)
  scrollToAnchor(id)
}

/* 滚动到锚点 */
const scrollToAnchor = (id: string) => {
  const target = document.getElementById(id)
  if (!target) return

  // 获取元素顶部位置（相对文档顶部）
  const targetTop = target.getBoundingClientRect().top + window.scrollY

  // 计算最终位置（下移60px）
  const offsetPosition = targetTop - 60

  // 平滑滚动
  window.scrollTo({
    top: offsetPosition,
    behavior: 'smooth'
  })
}

const handleChildSelect = (node: TreeNode) => {
  emit('select', node);
};
</script>

<style lang="less" scoped>
.node-container {
  font-size: 14px;
  line-height: 20px;
  cursor: pointer;

  .node-content {
    padding: 6px 12px;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: all 0.2s;
    margin: 2px 0;

    .node-title {
      margin-left: 8px;
      font-weight: 400;
    }

    &:hover {
      background: #eb5c88;
      color: #ffffff;
    }

    &.selected {
      background: #f8e1e7;
      color: #eb5c88;
    }

    .toggle-icon {
      font-size: 12px;
      margin-left: 8px;
    }
  }

  .children-container {
    margin-left: 12px;
    //border-left: 1px dashed #e0e0e0;
  }
}
</style>
